package com.zyx.mall.controller;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.zyx.mall.entity.Tuku;
import com.zyx.mall.service.TukuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 图片
 * </p>
 *
 * @author zyx
 * @since 2022-12-29
 */
@RestController
@RequestMapping("/api/tuku")
public class TukuController {

    @Autowired
    private TukuService tukuService;

    @Value("${web.uploadPath}")
    private String baseUploadPath;

    //上传图片
    @PostMapping("/upload")
    public Boolean uploadFile(@RequestBody Tuku tuku) {
        //获取图片对象的base64字符串
        String base64 = tuku.getBase64();
        //把base64分割成字符串数组
        String[] dataArray = StrUtil.splitToArray(base64, "base64,");
        //把图片的数据转化成字节数组
        byte[] bytes = Base64.decode(dataArray[1]);
        //获取图片的名字
        String name = tuku.getName();
        //给图片取个随机新的名字，防止同名覆盖
        String newName = IdUtil.fastSimpleUUID() + "_" + name;
        //把图片写入本地
        FileUtil.writeBytes(bytes,baseUploadPath+newName);
        //设置图片对象的地址
        tuku.setImg("http://localhost:8080/images/"+newName);
        //把图片的信息存入数据库
        return tukuService.save(tuku);
    }

    //获取图库的所有图片
    @GetMapping("/list")
    public List<Tuku> GetList() {
        List<Tuku> list = tukuService.list(null);
        return list;
    }

    //修改图片
    @PutMapping("/update")
    public Boolean updateTuku(@RequestBody Tuku tuku) {
        return tukuService.updateById(tuku);
    }

    //删除图片
    @DeleteMapping("/del/{id}")
    public Boolean delTuku(@PathVariable String id){
        return tukuService.removeById(id);
    }

    //通过id获取图片
    @GetMapping("/getById/{id}")
    public Tuku getById(@PathVariable String id) {
        return tukuService.getById(id);
    }
}

